package com.example.myapp.Fragment;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.myapp.APP.Bianqin;
import com.example.myapp.Activity.Help;
import com.example.myapp.APP.Jizhangben;
import com.example.myapp.Activity.Login;
import com.example.myapp.Activity.MyArticles;
import com.example.myapp.Activity.Myfensi;
import com.example.myapp.Activity.Myguanzhu;
import com.example.myapp.Activity.Myhome;
import com.example.myapp.Activity.Myhuifu;
import com.example.myapp.Activity.Mypinglun;
import com.example.myapp.Activity.Myshoucang;
import com.example.myapp.Activity.Myzhuanfa;
import com.example.myapp.Activity.Notice;
import com.example.myapp.Activity.Setting;
import com.example.myapp.Model.AD;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Fensi;
import com.example.myapp.Model.User;
import com.example.myapp.R;

import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import de.hdodenhof.circleimageview.CircleImageView;

//import android.support.v4.app.Fragment;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SHOW_TEXT = "text";
    private  String objID;
    private   Banner banner;
    private  TextView tv_username;
    private  TextView tv_jianjie;
    private  TextView tv_yincang;
    private     TextView tv_count1;
    private     TextView tv_count2;
    private     TextView tv_count3;
    private CircleImageView head_image;
      private   BmobFile bmobFile;

    public UserFragment() {
        // Required empty public constructor
    }
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    String ionName = (String) msg.obj;
                    //head_image.setImageURI(Uri.parse(path));
                        //这里采取线程+消息下载到本机方法
                        bmobFile.download(new File(Environment.getExternalStorageDirectory(),bmobFile.getFilename()), new
                                DownloadFileListener() {
                                    @Override
                                    public void done(String s, BmobException e) {
                                        if (e == null) {
                                            Log.w("aaaa","请求网络图片"+s);
                                            head_image.setImageURI(Uri.parse(s));
                                        }
                                        else {
                                            Toast.makeText(getActivity(),"请求网络图片失败" +e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                    @Override
                                    public void onProgress(Integer integer, long l) {
                                    }
                                });
                    break;
                }
                case 2: {
                    queryALLguanzhu();
                    queryALLPost();
                    queryALLFensi();
                    Gobanner();  //广告录播图
                }  break;

            }
        }
    };
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment HomeFragment.
     */
    public static UserFragment newInstance(String param1) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHOW_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(BmobUser.isLogin()){
                objID = BmobUser.getCurrentUser(User.class).getObjectId();
        }

    }





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_user, container, false);
        ImageView setting = rootView.findViewById(R.id.setting);
        LinearLayout userhome = rootView.findViewById(R.id.userhome);
        LinearLayout tvdongtai = rootView.findViewById(R.id.tvdongtai);
        LinearLayout tv_guanzhu = rootView.findViewById(R.id.tv_guanzhu);
        LinearLayout tv_fen = rootView.findViewById(R.id.tv_fen);
        LinearLayout tv_notice = rootView.findViewById(R.id.tv_notice);
        LinearLayout iv_shoucang = rootView.findViewById(R.id.iv_shoucang);
        LinearLayout iv_zan = rootView.findViewById(R.id.iv_zan);
        LinearLayout iv_zhuanfa = rootView.findViewById(R.id.iv_zhuanfa);
        LinearLayout iv_pinglun = rootView.findViewById(R.id.iv_pinglun);
        LinearLayout iv_bangzhu = rootView.findViewById(R.id.iv_bangzhu);
        LinearLayout iv_jizhang = rootView.findViewById(R.id.iv_jizhang);
        LinearLayout iv_bianqian = rootView.findViewById(R.id.iv_bianqian);
        LinearLayout iv_kefu = rootView.findViewById(R.id.iv_kefu);
        banner = rootView.findViewById(R.id.banner);
         tv_username=rootView.findViewById(R.id.tv_username);
        tv_jianjie=rootView.findViewById(R.id.tv_jianjie);
        head_image=rootView.findViewById(R.id.head_image);
        tv_yincang=rootView.findViewById(R.id.tv_yincang);
        tv_count1=rootView.findViewById(R.id.tv_count1);
        tv_count2=rootView.findViewById(R.id.tv_count2);
        tv_count3=rootView.findViewById(R.id.tv_count3);


        init();// 页面初始化
        Message message = new Message();
        message.what = 2;
        handler.sendMessage(message);
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), Setting.class));
            }
        });
        userhome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    startActivity(new Intent(getActivity(), Login.class));

                }else {
                    startActivity(new Intent(getActivity(), Myhome.class));
                }


            }


        });    // 主页
        tvdongtai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), MyArticles.class));
            }
        });    // 动态
        tv_guanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Myguanzhu.class));
            }
        });    // 关注
        tv_fen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Myfensi.class));

            }
        });    // 粉丝
        iv_shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Myshoucang.class));
            }
        });//收藏
        iv_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Myhuifu.class));
            }
        });//点赞
        iv_zhuanfa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Myzhuanfa.class));
            }
        });//转发
        iv_pinglun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Mypinglun.class));
            }
        });//评论
        iv_bangzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Help.class));
            }
        });//课表
        iv_jizhang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Jizhangben.class));
            }
        });//记账
        iv_bianqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(new Intent(getActivity(), Bianqin.class));
            }
        });//便签
        iv_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {

                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=1484772977";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {

                    Toast.makeText(getActivity(),"请先安装QQ",Toast.LENGTH_SHORT).show();
                }
//                Intent intent = new Intent(getActivity(), Chat.class);
//                intent.putExtra("userID", "5ac31aebdc");
//                intent.putExtra("jianJie","有事没事随时都可以来打扰我哦！");
//                intent.putExtra("iconUrl","http://wen.mangoroom.cn/2020/07/23/d7338cf8408e633280bfc56b393ae4d0.png");
//                intent.putExtra("userName","莆院帮小文");
//                intent.putExtra("isUserPagecome","yes");
//                startActivity(intent);
            }
        });//客服


        tv_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!BmobUser.isLogin()){
                    Toast.makeText(getActivity(), "请登陆后再操作！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(getActivity(), Notice.class);
                intent.putExtra("title", "莆院帮管理规范");//打开主页
                intent.putExtra("path", "file:///android_asset/notice.html");//打开主页
                startActivity(intent);
            }
        });//通知


        return rootView;
    }

    /**
     查询一对多，我的所有动态
     */
    private void queryALLPost(){
        if (BmobUser.isLogin()) {
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            BmobQuery<Article> query = new BmobQuery<>();
            query.addWhereEqualTo("author",new BmobPointer(BmobUser.getCurrentUser(User.class)));
            query.include("user,author,article");
            query.findObjects(new FindListener<Article>() {
                @Override
                public void done(List<Article> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "查询我的动态成功"+object.size());
                        tv_count1.setText(""+object.size());
//                        Log.w("aaaa", ""+ user.getUsername());
                    } else {
                        Log.e("aaaa","查询我的动态失败"+ e.getMessage());

                    }
                }

            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }


    /**
     * 查询我所有关注
     */
    private void queryALLguanzhu(){
        if (BmobUser.isLogin()) {
            BmobQuery<User> query = new BmobQuery<User>();
            // 用此方式可以构造一个BmobPointer对象。只需要设置objectId就行
            User user = BmobUser.getCurrentUser(User.class);//查自己
            query.addWhereRelatedTo("friend", new BmobPointer(user));
            //包含作者信息
            query.include("user,author");
            query.findObjects(new FindListener<User>() {
                @Override
                public void done(List<User> object, BmobException e) {
                    if (e == null) {
                        Log.w("aaaa", "我的主页关注个数"+object.size());
                        tv_count2.setText(""+object.size());
                    } else {
                        Log.e("aaaa","我的主页友关注失败"+ e.getMessage());
                    }
                }
            });
        } else {
            Log.w("aaaa", "请先登录！");
        }
    }

    /**
     查询一对多，我的所有粉丝
     */
    //查询一对多，一个帖子的所有评论
    private void queryALLFensi(){
        if(!BmobUser.isLogin()){
            return;
        }
        BmobQuery<Fensi> query_fs = new BmobQuery<>();
        query_fs.addWhereEqualTo("user", BmobUser.getCurrentUser(User.class).getObjectId());
       // query_fs.include("user");
        query_fs.findObjects(new FindListener<Fensi>() {
            @Override
            public void done(List<Fensi> object, BmobException e) {
                if (e == null) {
                    Log.w("aaaa", "查询评论成功！"+object);
                    tv_count3.setText(""+object.size());

                } else {
                    Log.e("aaaa","查询评论失败"+ e.getMessage());
                }
            }
        });
    }


    //页面初始化
    private  void init(){
        if(!BmobUser.isLogin()){
            tv_username.setText("未登录，去登录");
            return;
        }
        //创建查询对象和下载头像
        BmobQuery<User> query = new BmobQuery<User>();
        query.include("friend");
        query.getObject(objID, new QueryListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                String name= user.getUsername();
                tv_username.setText(name);
                String str= user.getShow();
                if (str.length()>14){
                    tv_yincang.setVisibility(View.VISIBLE);//mlistview2处于显示状态
                    tv_jianjie.setText("简介："+str.substring(0,11));
                }else {
                    tv_jianjie.setText("简介："+str);
                }

                Glide.with(getActivity()).load(user.getIcon().getUrl()).into(head_image);


            }
        });
    }
    // 判断是否已经有头像
    private   boolean isHaveIcon(String filename) {
        //首先判断外部存储是否可用
        String SDPATH = Environment.getExternalStorageDirectory().getPath()+"//";
        try {
            File file=new File(SDPATH+filename);
            if(!file.exists()){
                return false;
            }
        }catch (Exception e){
            // TODO: handle exception
            return false;
        }
        return true;
    }
    //广告录播图
    private   void Gobanner(){
        final   ArrayList<String> imgs = new ArrayList<>();
        final   ArrayList<String> title = new ArrayList<>();
        BmobQuery<AD> bmobQuery = new BmobQuery<AD>();
        bmobQuery.getObject("QUAdCCCM", new QueryListener<AD>() {
            @Override
            public void done(AD object,BmobException e) {
                if(e==null){
                    Log.w("aaaa","查询成功");
                    imgs.add(object.getImg1().getFileUrl());
                    imgs.add(object.getImg2().getFileUrl());
                    imgs.add(object.getImg3().getFileUrl());
                    imgs.add(object.getImg4().getFileUrl());
                    title.add(object.getTitle1());
                    title.add(object.getTitle2());
                    title.add(object.getTitle3());
                    title.add(object.getTitle4());

                    banner.setImages(imgs);
                    banner.setImageLoader(new ImageLoadBanner());
                    banner.setBannerTitles(title);
                    banner.setDelayTime(3000);
                    banner.isAutoPlay(true);
                    banner.setIndicatorGravity(BannerConfig.CENTER);
                    banner.setBannerAnimation(Transformer.Accordion);
                    banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
                    banner.start();
                    banner.setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(int i) {
                        switch (i){
                            case 0:{
                                Uri uri = Uri.parse(object.getUrl1());
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                startActivity(intent);
                            }break;
                            case 1:{
                                Uri uri = Uri.parse(object.getUrl2());
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                startActivity(intent);
                            }break;
                            case 2:{
                                Uri uri = Uri.parse(object.getUrl3());
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                startActivity(intent);
                            }break;
                            case 3:{
                                Uri uri = Uri.parse(object.getUrl4());
                                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                                startActivity(intent);
                            }break;
                        }
                        }
                    });

                }else{
                    Log.w("aaaa","查询失败"+e.getMessage());
                }
            }
        });

    }
    //广告录播图图片渲染
     private   class ImageLoadBanner extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
//            这个是本地资源渲染
//            imageView.setImageResource(Integer.parseInt(path.toString()));
//            网络资源渲染
            Glide.with(context).load((String) path).into(imageView);
        }
    }
}